var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');
const {
  CollectList
} = require('../../config/api.js');

var app = getApp();

Page({
  data: {
    cartGoods: [],
    loseGoods: [],
    newGoods: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    leaderId: 0, //0团长未设置
    areaChecked: 0, //是否选了团长
    areaAddress: '',
    areaName: '',
    nickName: '',
    avatarUrl: '',
    isEditCart: false,
    checkedAllStatus: true, //是否全部选中
    editCartList: [],
    hasLogin: false
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function () {
    // 页面渲染完成
  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getCartList();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onShow: function () {
    // 页面显示
    if (app.globalData.hasLogin) {
      this.getCartList();
    }

    this.setData({
      hasLogin: app.globalData.hasLogin
    });
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  goHome() {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },
  getCartList: function () {
    let that = this;
    util.request(api.CartList).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          areaChecked: res.data.checked,
          areaAddress: res.data.leaderInfo.address,
          areaName: res.data.leaderInfo.areaName,
          nickName: res.data.leaderInfo.nickName,
          avatarUrl: res.data.leaderInfo.avatarUrl,
          leaderId: res.data.leaderInfo.leaderId,
          cartGoods: res.data.cartList,
          loseGoods: res.data.loseList,
          cartTotal: res.data.cartTotal
        });
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      }
    });

    //推荐商品
    util.request(api.GoodsRelated, {
      id: 0
    }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          newGoods: res.data.goodsList,
        });
      }
    });
  },
  isChildCheckedAll: function (cartList) {
    return cartList.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  isCheckedAll: function () {
    let that = this;
    //判断购物车商品已全选
    return that.data.cartGoods.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  doCheckedAll: function () {
    let checkedAll = this.isCheckedAll()
    this.setData({
      checkedAllStatus: this.isCheckedAll()
    });
  },
  getProductChecked: function (goodsId) {
    let that = this;
    let isChecked = null;
    that.data.cartGoods.forEach(function (o) {
      if (o.goodsId === goodsId) {
        isChecked = o.checked ? 0 : 1;
      }
    });
    return isChecked;
  },
  checkedItem: function (event) {
    let goodsId = event.currentTarget.dataset.goodsid;
    let that = this;
    let goodIds = [];
    goodIds.push(goodsId);
    let isChecked = that.getProductChecked(goodsId);
    util.request(api.CartChecked, {
      goodsId: goodIds,
      isChecked: isChecked
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        that.setData({
          cartGoods: res.data.cartList,
          loseGoods: res.data.loseList,
          cartTotal: res.data.cartTotal
        });
      } else {
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: res.errmsg,
          mask: true
        });
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  getCheckedGoodsCount: function () {
    let that = this;
    let checkedGoodsCount = 0;
    if (that.data.isMultiOrderModel === 1) {
      that.data.brandCartgoods.forEach(function (v) {
        v.cartList.forEach(function (o) {
          if (o.checked === true) {
            checkedGoodsCount += o.number;
          }
        });
      });
    } else {
      that.data.cartGoods.forEach(function (v) {
        if (v.checked === true) {
          checkedGoodsCount += v.number;
        }
      });
    }
    return checkedGoodsCount;
  },
  checkedAll: function () {
    let that = this;
    var goodIds = that.data.cartGoods.map(function (v) {
      return v.goodsId;
    });

    util.request(api.CartChecked, {
      goodsId: goodIds,
      isChecked: that.isCheckedAll() ? 0 : 1
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        that.setData({
          cartGoods: res.data.cartList,
          loseGoods: res.data.loseList,
          cartTotal: res.data.cartTotal
        });
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },

  updateCart: function (cartItem, goodsId, number, id) {
    let that = this;
    util.request(api.CartUpdate, {
      goodsId: goodsId,
      number: number
    }, 'POST').then(function (res) {
      if (res.errno == 0) {
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
        cartItem.number = number;
      } else {
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: res.errmsg,
          mask: true
        });
      }
      that.getCartList();
    });
  },
  getProductItem: function (goodsId) {
    let that = this;
    let productItem = null;
    that.data.cartGoods.forEach(function (o) {
      if (o.goodsId === goodsId) {
        productItem = o;
      }
    });
    return productItem;
  },
  setProductItem: function (cartItem, goodsId) {
    let that = this;
    let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
      if (element.goodsId === goodsId) {
        return cartItem;
      } else {
        return element;
      }
    });
    that.setData({
      cartGoods: tmpCartData,
      checkedAllStatus: that.isCheckedAll(),
      'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
    });
  },
  cutNumber: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let goodsId = event.currentTarget.dataset.goodsid;
    let cartItem = this.getProductItem(goodsId);
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    this.setProductItem(cartItem, goodsId);
    this.updateCart(cartItem, cartItem.goodsId, number, cartItem.id);
  },
  addNumber: function (event) {
    let goodsId = event.currentTarget.dataset.goodsid;
    let cartItem = this.getProductItem(goodsId);
    let number = cartItem.number + 1;
    cartItem.number = number;
    this.setProductItem(cartItem, goodsId);
    this.updateCart(cartItem, cartItem.goodsId, number, cartItem.id);
  },
  checkoutOrder: function () {
    //获取已选择的商品
    let that = this;
    if (that.getCheckedGoodsCount() <= 0) {
      wx.showModal({
        title: '错误信息',
        content: '请勾选需要下单的商品！',
        showCancel: false
      });
      return false;
    }

    // storage中设置了cartId，则是购物车购买
    try {
      //购物车ID
      wx.setStorageSync('cartId', 0);
      //优惠券
      wx.setStorageSync('couponId', 0);
      //非团购为0
      wx.setStorageSync('grouponRulesId', 0);
      //该组团购标识，非团购-1
      wx.setStorageSync('grouponId', -1);
      wx.navigateTo({
        url: '/pages/checkout/checkout'
      })
    } catch (e) {}

  },

  //删除
  delGoods: function (e) {
    let that = this;
    util.request(api.CartDelete, {
      goodsId: [e.currentTarget.dataset.id]
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        wx.showToast({
          title: '删除成功'
        });
        that.setData({
          cartGoods: res.data.cartList,
          loseGoods: res.data.loseList,
          cartTotal: res.data.cartTotal
        });
      }
    });
  },
  //一键清空
  delAllLose: function () {
    let that = this;
    util.request(api.CartDelete, {
      goodsId: ['0']
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        wx.showToast({
          title: '清空成功'
        });
        that.setData({
          cartGoods: res.data.cartList,
          loseGoods: res.data.loseList,
          cartTotal: res.data.cartTotal
        });
      }
      //刷新购物车
      that.getCartList();
    });
  },
  // 加入购物车
  addCard: function (event) {
    let that = this;
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    } else { //添加到购物车
      var gId = event.currentTarget.id;
      console.log(gId);
      util.request(api.CartAdd, {
        goodsId: gId,
        number: 1
      }, "POST").then(function (res) {
        let _res = res;
        if (_res.errno == 0) {
          that.setData({
            number: res.data.number,
            money: res.data.money
          });
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }
      });
      //刷新购物车
      that.getCartList();
    }
  },
  //选择团长
  selectLeader(event) {
    var leaderId = event.currentTarget.dataset.leaderid;
    var latitude = "",
      longitude = "";
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res.latitude);
        latitude = res.latitude;
        longitude = res.longitude
      },
      fail: function (res) {
        console.log("--fail");
        wx.getSetting({
          success: function (res) {
            var statu = res.authSetting;
            console.log(statu);
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置，请确认授权，否则团长功能将无法使用',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //授权成功之后，再调用chooseLocation选择地方
                          wx.chooseLocation({
                            success: function (res) {
                              obj.setData({
                                addr: res.address
                              })
                            },
                          })
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            console.log("--fail");
            wx.showToast({
              title: '调用授权窗口失败',
              icon: 'success',
              duration: 1000
            })
          }
        })
      },
      complete: function (res) {
        console.log(latitude);
        wx.navigateTo({
          url: '/pages/ucenter/leader/leader?jd=' + longitude + '&wd=' + latitude + '&leaderId=' + leaderId,
        })
      }
    })
  },
})